package com.xmut.mall.member.service.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.member.dao.MemberCouponRelationDao;
import com.xmut.mall.member.entity.MemberCouponRelationEntity;
import com.xmut.mall.member.feign.CouponFeignService;
import com.xmut.mall.member.service.MemberCouponRelationService;
import com.xmut.mall.member.utils.Query;
import com.xmut.mall.member.utils.RespBean;
import com.xmut.mall.member.vo.CouponVo;
import com.xmut.mall.member.vo.MemberCouponVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("MemberCouponRelationService")
public class MemberCouponRelationServiceImpl extends ServiceImpl<MemberCouponRelationDao, MemberCouponRelationEntity> implements MemberCouponRelationService {

    @Autowired
    private CouponFeignService couponFeignService;

    /**
     * 用户领取优惠券
     *
     * @param memberId
     * @param couponId
     * @return
     */
    @CacheEvict(value = "UserCoupon",key = "#root.args[0]")
    @Override
    public RespBean receiveCoupon(Long memberId, Long couponId) {
        // 前置判断 防止重复领取
        int count = this.count(new QueryWrapper<MemberCouponRelationEntity>().eq("member_id", memberId).eq("coupon_id", couponId));
        System.out.println("数量:"+count);
        if(count!=0){
            return RespBean.error("请勿重复领取");
        }
        // 保存优惠券
        MemberCouponRelationEntity memberCouponRelation = new MemberCouponRelationEntity();
        memberCouponRelation.setMemberId(memberId);
        memberCouponRelation.setCouponId(couponId);
        memberCouponRelation.setReceiveTime(new Date());
        memberCouponRelation.setUsedFlag(0);
        boolean save = this.save(memberCouponRelation);
        if (save) {
            // 保存成功
            return RespBean.success("领取优惠券成功");
        } else {
            return RespBean.error("领取优惠券失败");
        }
    }

    @Cacheable(value = "UserCoupon", key = "#params.get('userId')")
    @Override
    public MemberCouponVo getUserCouponByPage(Map<String, Object> params) {
        QueryWrapper<MemberCouponRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("used_flag", params.get("usedFlag"));
        queryWrapper.eq("member_id", params.get("userId"));
        IPage<MemberCouponRelationEntity> page = this.page(
                new Query<MemberCouponRelationEntity>().getPage(params), queryWrapper
        );
        // 拿到分隔数据以后继续进行封装
        List<MemberCouponRelationEntity> relations = page.getRecords(); // 用户和优惠券之间的关联信息
        // 收集全部的优惠券id
        List<Long> collect = relations.stream().map(MemberCouponRelationEntity::getCouponId).distinct().collect(Collectors.toList());
        List<CouponVo> couponVos = new ArrayList<>();
        RespBean couponByIds = couponFeignService.getCouponByIds(collect);
        if (couponByIds.getCode() == 201) {
            // 转换数据
            couponVos = JSON.parseObject(JSON.toJSONString(couponByIds.getObj()), new TypeReference<List<CouponVo>>() {
            });
            // 设置该优惠券的使用情况（必须在这个vo不为空的情况下）
            if (couponVos!=null) {
                for (CouponVo coupon : couponVos) {
                    for (MemberCouponRelationEntity relation : relations) {
                        if (coupon.getId() == relation.getCouponId()) {
                            coupon.setUsedFlag(relation.getUsedFlag());
                        }
                    }
                }
            }
        }
        MemberCouponVo vo = new MemberCouponVo();
        vo.setCurrPage(page.getCurrent());
        vo.setPageSize(page.getSize());
        vo.setRecords(couponVos);
        // 有可能出现查出空的情况
        if(couponVos!=null){
            vo.setTotal(couponVos.size());
        }else {
            vo.setTotal(0);
        }

        return vo;
    }

    /**
     * 查询用户领取了几次当前id的优惠券
     * @param couponId
     * @param userId
     * @return
     */
    @Override
    public RespBean getUserReceiveCouponNum(Long couponId, Long userId) {
        int count = this.count(new QueryWrapper<MemberCouponRelationEntity>()
                .eq("member_id", userId)
                .eq("coupon_id", couponId));

        return RespBean.success("获取成功",count);

    }

    /**
     * 用户领取优惠券
     * @param params
     * @return
     */
    @Override
    public RespBean userReceiveCoupon(Map<String, Object> params) {
        Long userId = MapUtil.getLong(params, "userId");
        Long couponId = MapUtil.getLong(params, "couponId");

        MemberCouponRelationEntity entity = new MemberCouponRelationEntity();

        entity.setCouponId(couponId);
        entity.setMemberId(userId);
        entity.setReceiveTime(new Date());
        entity.setUsedFlag(0);

        boolean save = this.save(entity);
        if (save){
            return RespBean.success("保存成功");
        }else {
            return RespBean.error("保存失败");
        }


    }




}
